<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.1.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/green/pace-theme-minimal.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"liukairui.me","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.10.1","exturl":false,"sidebar":{"position":"left","display":"hide","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":true,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":false,"nav":null,"activeClass":"valine"},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="网上说的&quot;对于原始类型, 数据本身是存在栈内, 对于对象类型, 在栈中存的只是一个堆内地址的引用&quot;似乎有些不妥. 我们将讨论什么样的变量有资格存储在栈中, 存储在栈中的元素究竟存的是字面量还是引用.">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript变量存储机制">
<meta property="og:url" content="http://liukairui.me/article/JavaScript%E5%8F%98%E9%87%8F%E5%AD%98%E5%82%A8%E6%9C%BA%E5%88%B6/">
<meta property="og:site_name" content="LiuKairui Website">
<meta property="og:description" content="网上说的&quot;对于原始类型, 数据本身是存在栈内, 对于对象类型, 在栈中存的只是一个堆内地址的引用&quot;似乎有些不妥. 我们将讨论什么样的变量有资格存储在栈中, 存储在栈中的元素究竟存的是字面量还是引用.">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-02-28T16:00:01.000Z">
<meta property="article:modified_time" content="2022-03-02T02:15:06.012Z">
<meta property="article:author" content="Liu Kairui">
<meta property="article:tag" content="前端">
<meta property="article:tag" content="JS语法">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://liukairui.me/article/JavaScript%E5%8F%98%E9%87%8F%E5%AD%98%E5%82%A8%E6%9C%BA%E5%88%B6/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://liukairui.me/article/JavaScript%E5%8F%98%E9%87%8F%E5%AD%98%E5%82%A8%E6%9C%BA%E5%88%B6/","path":"article/JavaScript变量存储机制/","title":"JavaScript变量存储机制"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>JavaScript变量存储机制 | LiuKairui Website</title>
  

  <script src="/js/third-party/analytics/baidu-analytics.js"></script>
  <script async src="https://hm.baidu.com/hm.js?ea07bceb8f5fa721da2ebf01833faa32"></script>



<div class="nindexBK">
<div class="nindexBKC"></div>
<div class="nindex">
  <h1>Hey👋</h1>
  <p style="font-weight: 500; font-size: 2.2em">欢迎访问Liu Kairui的个人站.</p>
  <p>
      我是一个来自重庆的在校大学生, 偏爱于前端技术<!--与OS设计-->, 偶尔使用 JS / Go 进行轻量项目开发, 欢迎访问我的
      <a href="https://github.com/KairuiLiu" target="_blank"><i class="fab fa-github-alt"></i> GitHub</a> .
  </p>
  <p>
      这个网站主要用来存储学习 / 瞎搞的笔记, 同时提供了邮件、图床等服务. 对于一些自认为有趣的<a href="javascript:;" id="myProj">项目</a>, 我也会将项目介绍, 文档, 甚至是设计指南发布在这里.
  </p>
  <ul>
    <li><p><a href="/artrank/" target="_blank">ArtRank</a>: 基于Node.JS的PageRank文献管理推荐系统</p></li>
    <li><p><a href="/gooj/" target="_blank">GoOJ</a>: 基于Golang的高校在线评测系统</p></li>
    <li><p><a href="/projects/" target="_blank">更多 <i class="fas fa-angle-right"></i></a></p></li>

  </ul>
  <p>
      可以在这些平台找到我: 
      <a href="https://www.zhihu.com/people/liu-kai-rui-18" target="_blank">知乎</a>,
      <a href="https://space.bilibili.com/33238144" target="_blank">bilibili</a>
      和
      <a href="https://www.coolapk.com/u/805314?from=qr" target="_blank">酷安</a>.
  </p>

  <p>
      下滑即可进入博客 <i class="fas fa-arrow-down"></i>
  </p>
</div>
</div>  

 
<script>
  var OriginTitile = document.title;
  var titleTime;
  document.addEventListener("visibilitychange", function() {
    if (document.hidden) {
      document.title = "谢谢离开 | " + OriginTitile;
      clearTimeout(titleTime);
    } else {
      document.title = "欢迎归来 | " + OriginTitile;
      titleTime = setTimeout(function() {
        document.title = OriginTitile;
      }, 2000);
    }
  });
</script>


<script>
  function checkIndex(){
    let nindexItems = [[".nindexBK","display","block","none"],[".headband","display","none","block"],["div.toggle.sidebar-toggle","visibility","hidden","visible"]]; // ,["button.darkmode-toggle","visibility","hidden","visible"]];
    let isIndex = new RegExp("^(\/){0,1}(index){0,1}(\.html){0,1}(/)*$").test(location.pathname);
    let backCanvas = document.querySelector(".nindexBK");
    nindexItems.dispShift = function (stat){this.forEach((e) => {try{document.querySelector(e[0]).style[e[1]]=e[2+stat];}catch{}})}
    if(isIndex){
      nindexItems.dispShift(0);
      window.onscroll=function(){
        if(document.documentElement.scrollTop>backCanvas.offsetHeight*1.05){
          nindexItems.dispShift(1);window.onscroll=null;
        }
      }
      document.querySelector("#myProj").onclick=()=>{
        let projlist = document.querySelector(".nindex>ul");
        projlist.className.indexOf("ulactive")==-1?projlist.classList.add("ulactive"):projlist.classList.remove("ulactive")
      }
    }else nindexItems.dispShift(1);
  }
  checkIndex();
</script>

<!--<script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>-->

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<link rel="alternate" href="/atom.xml" title="LiuKairui Website" type="application/atom+xml">
<style>.darkmode--activated{--body-bg-color:#282828;--content-bg-color:#333;--card-bg-color:#555;--text-color:#ccc;--blockquote-color:#bbb;--link-color:#ccc;--link-hover-color:#eee;--brand-color:#ddd;--brand-hover-color:#ddd;--table-row-odd-bg-color:#282828;--table-row-hover-bg-color:#363636;--menu-item-bg-color:#555;--btn-default-bg:#222;--btn-default-color:#ccc;--btn-default-border-color:#555;--btn-default-hover-bg:#666;--btn-default-hover-color:#ccc;--btn-default-hover-border-color:#666;--highlight-background:#282b2e;--highlight-foreground:#a9b7c6;--highlight-gutter-background:#34393d;--highlight-gutter-foreground:#9ca9b6}.darkmode--activated img{opacity:.75}.darkmode--activated img:hover{opacity:.9}.darkmode--activated code{color:#69dbdc;background:0 0}button.darkmode-toggle{z-index:9999}.darkmode-ignore,img{display:flex!important}</style></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">LiuKairui Website</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">要有信仰</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fas fa-hashtag fa-fw"></i>标签</a></li>
        <li class="menu-item menu-item-收藏夹"><a href="/favorites/" rel="section"><i class="fab fa-gratipay fa-fw"></i>收藏夹</a></li>
        <li class="menu-item menu-item-留言板"><a href="/messageBoard/" rel="section"><i class="fab fa-facebook-messenger fa-fw"></i>留言板</a></li>
        <li class="menu-item menu-item-项目"><a href="/projects/" rel="section"><i class="fa fa-satellite fa-fw"></i>项目</a></li>
        <li class="menu-item menu-item-图床"><a href="http://img.liukairui.me/" rel="noopener" target="_blank"><i class="fa fa-bed fa-fw"></i>图床</a></li>
        <li class="menu-item menu-item-云ide"><a href="http://vsc.liukairui.me/" rel="noopener" target="_blank"><i class="fas fa-code fa-fw"></i>云IDE</a></li>
        <li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li>
        <li class="menu-item menu-item-邮箱"><a href="http://mail.liukairui.me/mail" rel="noopener" target="_blank"><i class="fas fa-envelope-open-text fa-fw"></i>邮箱</a></li>
        <li class="menu-item menu-item-rss"><a href="/atom.xml" rel="section"><i class="fa fa-rss fa-fw"></i>RSS</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A0%86%E4%B8%8E%E6%A0%88"><span class="nav-number">1.</span> <span class="nav-text">堆与栈</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B1%80%E9%83%A8%E5%85%A8%E5%B1%80%E9%97%AD%E5%8C%85%E5%8F%98%E9%87%8F%E7%9A%84%E5%AD%98%E5%82%A8%E6%9C%BA%E5%88%B6"><span class="nav-number">2.</span> <span class="nav-text">局部&#x2F;全局&#x2F;闭包变量的存储机制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%8D%E5%90%8C%E7%B1%BB%E5%9E%8B%E5%8F%98%E9%87%8F%E7%9A%84%E5%AD%98%E5%82%A8%E6%9C%BA%E5%88%B6"><span class="nav-number">3.</span> <span class="nav-text">不同类型变量的存储机制</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#string%E7%B1%BB%E5%9E%8B"><span class="nav-number">3.1.</span> <span class="nav-text">String类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#number"><span class="nav-number">3.2.</span> <span class="nav-text">Number</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#oddball-%E7%B1%BB%E5%9E%8B%E4%B8%8E-boolean-undefined-null"><span class="nav-number">3.3.</span> <span class="nav-text">OddBall 类型与 Boolean
&amp; Undefined &amp; null</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="nav-number">4.</span> <span class="nav-text">参考资料</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Liu Kairui"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Liu Kairui</p>
  <div class="site-description" itemprop="description">LiuKairui Persional Website</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">45</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">24</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">53</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/KairuiLiu" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;KairuiLiu" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:tclkr@live.com" title="E-Mail → mailto:tclkr@live.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://qm.qq.com/cgi-bin/qm/qr?k=oaf3ToOlN17hr5sHV98bT8qxsNYGaw5L&noverify=0" title="QQ → https:&#x2F;&#x2F;qm.qq.com&#x2F;cgi-bin&#x2F;qm&#x2F;qr?k&#x3D;oaf3ToOlN17hr5sHV98bT8qxsNYGaw5L&amp;noverify&#x3D;0" rel="noopener" target="_blank"><i class="fab fa-qq fa-fw"></i>QQ</a>
      </span>
      <span class="links-of-author-item">
        <a href="/atom.xml" title="RSS → &#x2F;atom.xml"><i class="fa fa-rss fa-fw"></i>RSS</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://liukairui.blog.csdn.net/" title="CSDN → https:&#x2F;&#x2F;liukairui.blog.csdn.net" rel="noopener" target="_blank"><i class="fab fa-cuttlefish fa-fw"></i>CSDN</a>
      </span>
      <span class="links-of-author-item">
        <a href="http://liukairui.cc/" title="国内站点 → http:&#x2F;&#x2F;liukairui.cc" rel="noopener" target="_blank"><i class="fa fa-globe fa-fw"></i>国内站点</a>
      </span>
  </div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdnjs.cloudflare.com/ajax/libs/creativecommons-vocabulary/2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>


  <div class="links-of-blogroll site-overview-item animated">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://paste.ubuntu.com/" title="https:&#x2F;&#x2F;paste.ubuntu.com&#x2F;" rel="noopener" target="_blank">Ubuntu Pastebin</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://send.firefox.com/" title="https:&#x2F;&#x2F;send.firefox.com&#x2F;" rel="noopener" target="_blank">Firefox Send</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://jkwzs.cn/" title="https:&#x2F;&#x2F;jkwzs.cn&#x2F;" rel="noopener" target="_blank">南花醉笔丶の个人博客</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://ywrby.cn/" title="https:&#x2F;&#x2F;ywrby.cn&#x2F;" rel="noopener" target="_blank">Ywrby个人博客</a>
        </li>
    </ul>
  </div>

        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://liukairui.me/article/JavaScript%E5%8F%98%E9%87%8F%E5%AD%98%E5%82%A8%E6%9C%BA%E5%88%B6/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Liu Kairui">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="LiuKairui Website">
      <meta itemprop="description" content="LiuKairui Persional Website">
    </span>
    
    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="JavaScript变量存储机制 | LiuKairui Website">
      <meta itemprop="description" content="网上说的"对于原始类型, 数据本身是存在栈内, 对于对象类型, 在栈中存的只是一个堆内地址的引用"似乎有些不妥. 我们将讨论什么样的变量有资格存储在栈中, 存储在栈中的元素究竟存的是字面量还是引用.">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          JavaScript变量存储机制
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-03-01 00:00:01" itemprop="dateCreated datePublished" datetime="2022-03-01T00:00:01+08:00">2022-03-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">前端</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%89%8D%E7%AB%AF/JS%E8%AF%AD%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">JS语法</span></a>
        </span>
    </span>

  
    <span id="/article/JavaScript%E5%8F%98%E9%87%8F%E5%AD%98%E5%82%A8%E6%9C%BA%E5%88%B6/" class="post-meta-item leancloud_visitors" data-flag-title="JavaScript变量存储机制" title="阅读次数">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span class="leancloud-visitors-count"></span>
    </span>
  
  <span class="post-meta-item">
    
    <span class="post-meta-item-icon">
      <i class="far fa-comment"></i>
    </span>
    <span class="post-meta-item-text">Valine：</span>
  
    <a title="valine" href="/article/JavaScript%E5%8F%98%E9%87%8F%E5%AD%98%E5%82%A8%E6%9C%BA%E5%88%B6/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/article/JavaScript%E5%8F%98%E9%87%8F%E5%AD%98%E5%82%A8%E6%9C%BA%E5%88%B6/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

<script>
    CONFIG.hostname = location.hostname;
</script>
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>7k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>6 分钟</span>
    </span>
</div>

            <div class="post-description">网上说的"对于原始类型, 数据本身是存在栈内, 对于对象类型, 在栈中存的只是一个堆内地址的引用"似乎有些不妥. 我们将讨论什么样的变量有资格存储在栈中, 存储在栈中的元素究竟存的是字面量还是引用.</div>
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>本文分两个部分讨论变量存储模式</p>
<ul>
<li>局部/ 全局/ 闭包变量的存储机制:
在这部分我们讨论什么样的变量有资格存储在栈中</li>
<li>不同类型变量的存储机制:
在这部分我们讨论存储在栈中的元素究竟存的是字面量还是引用</li>
</ul>
<p>先说结论: 万物都存在堆中, 有的变量会在栈上存储引用地址</p>
<h3 id="堆与栈">堆与栈</h3>
<ul>
<li>堆是一个很大的内存存储空间, 你可以在里面存储任何类型数据.
操作系统不会自动回收. 在栈中存储不了的数据比如对象就会被存储在堆中,
在栈中呢是保留了对象在堆中的地址, 也就是对象的引用.</li>
<li>栈是内存中一块用于<strong>存储局部变量和函数参数的线性结构</strong>,
遵循着先进后出的原则. 数据只能顺序的入栈, 顺序的出栈. 内存中栈区的数据,
在函数调用结束后, 就会自动的出栈, 不需要程序进行操作,
操作系统会自动回收</li>
</ul>
<p>于是出现了一个问题, 在闭包出现时,
函数是如何访问到闭包所在的已经销毁的栈中的变量的呢?</p>
<h3 id="局部全局闭包变量的存储机制">局部/全局/闭包变量的存储机制</h3>
<ul>
<li><p>局部变量: 最简单的, 局部变量存储在作用域所在的栈空间中, 例如
<pre class="language-js" data-language="js"><code class="language-js"><span class="token keyword">function</span> <span class="token function">demo</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
  <span class="token keyword">let</span> a <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
  <span class="token keyword">let</span> b <span class="token operator">=</span> <span class="token string">'213'</span><span class="token punctuation">;</span>
  <span class="token keyword">let</span> c <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">213</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  <span class="token keyword">let</span> d <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Object</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>

console<span class="token punctuation">.</span><span class="token function">dir</span><span class="token punctuation">(</span>demo<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// ƒ demo()</span>
<span class="token comment">//   arguments: null</span>
<span class="token comment">//   caller: null</span>
<span class="token comment">//   length: 0</span>
<span class="token comment">//   name: "demo"</span>
<span class="token comment">//   prototype:</span>
<span class="token comment">//     constructor: ƒ demo()</span>
<span class="token comment">//     [[Prototype]]: Object</span>
<span class="token comment">//   [[FunctionLocation]]: demo.html:53</span>
<span class="token comment">//   [[Prototype]]: ƒ ()</span>
<span class="token comment">//   [[Scopes]]: Scopes[1]</span>
<span class="token comment">//     0: Global &#123;0: Window, window: Window, self: Window, document: document,</span></code></pre> 在上面我们找不到定义的变量,
在DevTools的内存-堆分析中也找不到他们</p></li>
<li><p>全局变量</p>
<ul>
<li>使用<code>var</code>声明的全局变量<br />
使用<code>var</code>声明全局变量其实仅仅是为<code>global</code>对象添加了一条属性,
全局变量会被默认添加到函数作用域链的最底端,
也就是<code>[[Scopes]]</code>中的最后一个 <pre class="language-js" data-language="js"><code class="language-js"><span class="token keyword">var</span> aaa <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>          <span class="token comment">// 随便var一个变量</span>
<span class="token comment">// 等同于 window.aaa = 1;</span>
console<span class="token punctuation">.</span><span class="token function">dir</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">=></span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>   <span class="token comment">// 随便打印一个函数看看他的作用域</span>

<span class="token comment">// anonymous()</span>
<span class="token comment">//   length: 0</span>
<span class="token comment">//   name: ""</span>
<span class="token comment">//   arguments: (…)</span>
<span class="token comment">//   caller: (…)</span>
<span class="token comment">//   [[FunctionLocation]]: VM167:1</span>
<span class="token comment">//   [[Prototype]]: ƒ ()</span>
<span class="token comment">//   [[Scopes]]: Scopes[1]    &lt;- 看到函数的作用域</span>
<span class="token comment">//     0: Global              &lt;- 只有global(window)作用域</span>
<span class="token comment">//       aaa: 1               &lt;- 看到window上的aaa</span>
<span class="token comment">//       alert: ƒ alert()</span>
<span class="token comment">//       atob: ƒ atob()</span>
<span class="token comment">//       blur: ƒ blur()</span>
<span class="token comment">//       btoa: ƒ btoa()</span></code></pre></li>
<li>使用<code>let</code>/<code>const</code>声明全局变量不会修改<code>window</code>对象,
而是将变量的声明放在了一个特殊的对象<code>Script</code>下
<pre class="language-js" data-language="js"><code class="language-js"><span class="token keyword">let</span> t1 <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> t2 <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">;</span>
console<span class="token punctuation">.</span><span class="token function">dir</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">=></span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>

<span class="token comment">// anonymous()</span>
<span class="token comment">//   length: 0</span>
<span class="token comment">//   name: ""</span>
<span class="token comment">//   arguments: (…)</span>
<span class="token comment">//   caller: (…)</span>
<span class="token comment">//   [[FunctionLocation]]: VM99:1</span>
<span class="token comment">//   [[Prototype]]: ƒ ()</span>
<span class="token comment">//   [[Scopes]]: Scopes[2]      &lt;- 查看作用域</span>
<span class="token comment">//     0: Script &#123;t1: 1, t2: 2&#125;   &lt;- 看到这些数据被存储到了Script对象中</span>
<span class="token comment">//     1: Global &#123;window: Window, self: Window, document: document,...&#125;</span></code></pre></li>
</ul></li>
<li><p>闭包中的变量:
闭包中的变量会在子函数调用的时候存储为一个对象(存储在堆中),
并在<code>[[Scopes]]</code>的<code>Closure(闭包)</code>中体现
<pre class="language-js" data-language="js"><code class="language-js"><span class="token keyword">function</span> <span class="token function">testCatch1</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
  <span class="token keyword">let</span> a1 <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
  <span class="token keyword">var</span> a2 <span class="token operator">=</span> <span class="token string">'a'</span><span class="token punctuation">;</span>
  <span class="token keyword">const</span> a3 <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
  <span class="token keyword">let</span> a4 <span class="token operator">=</span> <span class="token punctuation">&#123;</span><span class="token literal-property property">a</span><span class="token operator">:</span> <span class="token number">1</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>a1<span class="token punctuation">,</span> a2<span class="token punctuation">,</span> a3<span class="token punctuation">,</span> a4<span class="token punctuation">)</span>
  <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">function</span> <span class="token function">testCatch2</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
<span class="token keyword">let</span> a1 <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
<span class="token keyword">var</span> a2 <span class="token operator">=</span> <span class="token string">'a'</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> a3 <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> a4 <span class="token operator">=</span> <span class="token punctuation">&#123;</span><span class="token literal-property property">a</span><span class="token operator">:</span> <span class="token number">1</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
<span class="token keyword">return</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>a1<span class="token punctuation">,</span> a2<span class="token punctuation">,</span> a3<span class="token punctuation">,</span> a4<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

console<span class="token punctuation">.</span><span class="token function">dir</span><span class="token punctuation">(</span><span class="token function">testCatch1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

<span class="token comment">// ƒ anonymous()</span>
<span class="token comment">//   arguments: null</span>
<span class="token comment">//   caller: null</span>
<span class="token comment">//   length: 0</span>
<span class="token comment">//   name: ""</span>
<span class="token comment">//   prototype: &#123;constructor: ƒ&#125;</span>
<span class="token comment">//   [[FunctionLocation]]: VM469:6</span>
<span class="token comment">//   [[Prototype]]: ƒ ()</span>
<span class="token comment">//   [[Scopes]]: Scopes[2]</span>
<span class="token comment">//     0: Closure (testCatch1) &#123;a1: 1, a2: 'a', a3: true, a4: &#123;…&#125;&#125;  &lt;- 可以看到是按照对象存储在堆中的 </span>
<span class="token comment">//     1: Global &#123;window: Window, self: Window, document: document, name: '',...&#125; &lt;- global在作用域最后</span>

console<span class="token punctuation">.</span><span class="token function">dir</span><span class="token punctuation">(</span><span class="token function">testCatch2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

<span class="token comment">// ƒ anonymous()</span>
<span class="token comment">//   arguments: null</span>
<span class="token comment">//   caller: null</span>
<span class="token comment">//   length: 0</span>
<span class="token comment">//   name: ""</span>
<span class="token comment">//   prototype: &#123;constructor: ƒ&#125;</span>
<span class="token comment">//   [[FunctionLocation]]: VM469:16</span>
<span class="token comment">//   [[Prototype]]: ƒ ()</span>
<span class="token comment">//   [[Scopes]]: Scopes[2]</span>
<span class="token comment">//     0: Closure (testCatch2) &#123;a1: 1, a2: 'a', a3: true, a4: &#123;…&#125;&#125; &lt;- 可以看到是按照对象存储在堆中的, 但是闭包名不同</span>
<span class="token comment">//     1: Global &#123;window: Window, self: Window, document: document, name: '',&#125;</span>

console<span class="token punctuation">.</span><span class="token function">dir</span><span class="token punctuation">(</span><span class="token function">testCatch1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>a4 <span class="token operator">===</span> <span class="token function">testCatch1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>a4<span class="token punctuation">)</span>

<span class="token comment">// true &lt;- 连引用对象都是相同的</span></code></pre></p></li>
</ul>
<p>小结: 除了局部变量, 其他变量都在堆中</p>
<p>那么, 栈中变量是如何存储的呢? 是如开头所说基本数据类型存字面值,
对象存引用地址吗?</p>
<h3 id="不同类型变量的存储机制">不同类型变量的存储机制</h3>
<ul>
<li>对于对象类型的数据, 毫无疑问: 栈中存储的是对象在堆中的地址</li>
<li>对于基础数据类型呢? 他存储的是字面量吗? 首先我们清楚基础类型包括
<ul>
<li>Number &amp; String &amp; Boolean</li>
<li>Null &amp; Undefined</li>
<li>Symbol &amp; BigInt</li>
</ul></li>
</ul>
<h4 id="string类型">String类型</h4>
<ul>
<li>首先创建两个包含string的对象 <pre class="language-js" data-language="js"><code class="language-js"><span class="token keyword">const</span> <span class="token function-variable function">BasicVarGen</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>s1 <span class="token operator">=</span> <span class="token string">'IAmString'</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>s2 <span class="token operator">=</span> <span class="token string">'IAmString'</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">let</span> a <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BasicVarGen</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">let</span> b <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BasicVarGen</span><span class="token punctuation">(</span><span class="token punctuation">)</span></code></pre>
切换到DevTools-内存-堆快照-BasicVarGen <pre class="language-js" data-language="js"><code class="language-js">BasicVarGen×<span class="token number">2</span>	

  BasicVarGen@<span class="token number">47647</span>
    <span class="token literal-property property">__proto__</span><span class="token operator">:</span><span class="token operator">:</span>Object@<span class="token number">52873</span>
    <span class="token literal-property property">map</span><span class="token operator">:</span><span class="token operator">:</span>system <span class="token operator">/</span> Map@<span class="token number">52877</span>
    <span class="token literal-property property">s1</span><span class="token operator">:</span><span class="token operator">:</span><span class="token string">"IAmString"</span>@<span class="token number">16065</span>🗖
    <span class="token literal-property property">s2</span><span class="token operator">:</span><span class="token operator">:</span><span class="token string">"IAmString"</span>@<span class="token number">16065</span>🗖
    
  BasicVarGen@<span class="token number">47649</span>
    <span class="token literal-property property">__proto__</span><span class="token operator">:</span><span class="token operator">:</span>Object@<span class="token number">52873</span>
    <span class="token literal-property property">map</span><span class="token operator">:</span><span class="token operator">:</span>system <span class="token operator">/</span> Map@<span class="token number">52877</span>
    <span class="token literal-property property">s1</span><span class="token operator">:</span><span class="token operator">:</span><span class="token string">"IAmString"</span>@<span class="token number">16065</span>🗖
    <span class="token literal-property property">s2</span><span class="token operator">:</span><span class="token operator">:</span><span class="token string">"IAmString"</span>@<span class="token number">16065</span>🗖</code></pre> 可以看到a,
b两个对象的虚拟地址不同,
但是s1与s2指向的虚拟地址都是<code>@16065</code>,
<strong>四个变量存储的都是引用地址</strong></li>
<li>继续实验, 尝试在新建对象后增加变量, 修改变量值 <pre class="language-js" data-language="js"><code class="language-js"><span class="token keyword">const</span> <span class="token function-variable function">BasicVarGen</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>s1 <span class="token operator">=</span> <span class="token string">'IAmstring'</span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>s2 <span class="token operator">=</span> <span class="token string">'IAmstring'</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">let</span> a <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BasicVarGen</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">let</span> b <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BasicVarGen</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">debugger</span>
a<span class="token punctuation">.</span>s0 <span class="token operator">=</span> <span class="token string">'different string'</span>
a<span class="token punctuation">.</span>s2 <span class="token operator">=</span> <span class="token string">'IAmstring1'</span>
b<span class="token punctuation">.</span>s1 <span class="token operator">=</span> <span class="token string">'IAmstring'</span>
b<span class="token punctuation">.</span>s2 <span class="token operator">=</span> <span class="token string">'IAm'</span> <span class="token operator">+</span> <span class="token keyword">typeof</span> <span class="token string">'111'</span></code></pre>
分别记录debugger前后内存, 比较 <pre class="language-diff" data-language="diff"><code class="language-diff">BasicVarGen×2	

<span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line"> BasicVarGen@64695
</span><span class="token prefix unchanged"> </span><span class="token line">   map::system / Map@67337
</span><span class="token prefix unchanged"> </span><span class="token line">   __proto__::Object@67331
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   s0::"different string"@16533🗖    &lt;- 新增的string有自己的地址
</span></span><span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line">   s1::"IAmstring"@64749🗖
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   s2::"IAmstring"@64749🗖
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   s2::"IAmstring1"@64745🗖    &lt;- string内容变化会导致地址变化
</span></span>
<span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line"> BasicVarGen@64697
</span><span class="token prefix unchanged"> </span><span class="token line">   map::system / Map@67337
</span><span class="token prefix unchanged"> </span><span class="token line">   __proto__::Object@67331
</span><span class="token prefix unchanged"> </span><span class="token line">   s1::"IAmstring"@64749🗖    &lt;- 赋相同值不会导致地址变化
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   s2::"IAmstring"@64749🗖    
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   s2::"IAmstring"@74797🗖    &lt;- 虽然字面量相同, 但是存储地址不同</span></span></code></pre></li>
</ul>
<p><strong>结论</strong></p>
<p>当我们声明一个字符串时:</p>
<ul>
<li>v8内部有一个名为stringTable的hashmap缓存了所有字符串,
在V8阅读我们的代码, 转换抽象语法树时, 每遇到一个字符串,
会根据其特征换算为一个hash值, 插入到hashmap中.
在之后如果遇到了hash值一致的字符串, 会优先从里面取出来进行比对,
一致的话就不会生成新字符串类.</li>
<li>缓存字符串时, 根据字符串不同采取不同hash方式.</li>
<li>字符串拼接时如果以传统方式(如SeqString)存储,
拼接操作的时间复杂度为O(n), 采用绳索结构(也就是 ConsString
所采用的数据结构)可以减少拼接所花费的时间, 但是不被hash为同一值.</li>
</ul>
<h4 id="number">Number</h4>
<p>数字在V8中分为<code>smi</code>和<code>heapNumber</code>.</p>
<ul>
<li><code>smi</code>直接存进内存, 范围为: <span
class="math inline">\(-2^{31}\sim 2^{31}-1\)</span>的整数</li>
<li><code>heapNumber</code>类似字符串, 范围为:
所有非<code>smi</code>的数字, 最低位用来表示是否为指针,
最低位为1则是一个指针 <pre class="language-js" data-language="js"><code class="language-js"><span class="token keyword">const</span> o <span class="token operator">=</span> <span class="token punctuation">&#123;</span>
  <span class="token literal-property property">x</span><span class="token operator">:</span> <span class="token number">42</span><span class="token punctuation">,</span>  <span class="token comment">// Smi</span>
  <span class="token literal-property property">y</span><span class="token operator">:</span> <span class="token number">4.2</span><span class="token punctuation">,</span> <span class="token comment">// HeapNumber</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">;</span></code></pre>
<code>o.x</code>中的<code>42</code>会被当成<code>Smi</code>直接存储在对象本身,
而<code>o.y</code>中的<code>4.2</code>需要额外开辟一个内存实体存放,
并将o.y的对象指针指向该内存实体.</li>
</ul>
<p>如果是32位操作系统, 用32位表示<code>smi</code>可以理解,
可是64位操作系统中, 为什么<code>smi</code>范围也是<span
class="math inline">\(-2^{31}\sim 2^{31}-1\)</span>? ECMAScript
标准约定<code>number</code>数字需要被当成64位双精度浮点数处理, 但事实上,
一直使用64位去存储任何数字实际是非常低效的(空间低效, 计算时间低效
<code>smi</code>大量使用位运算),
所以JavaScript引擎并不总会使用64位去存储数字,
引擎在内部可以采用其他内存表示方式(如32位),
只要保证数字外部所有能被监测到的特性对齐64位的表现就行.</p>
<p>套用之前的实验</p>
<pre class="language-js" data-language="js"><code class="language-js"><span class="token keyword">const</span> <span class="token function-variable function">BasicVarGen</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>smi1 <span class="token operator">=</span> <span class="token number">1</span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>smi2 <span class="token operator">=</span> <span class="token number">2</span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>heapNumber1 <span class="token operator">=</span> <span class="token number">1.1</span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>heapNumber2 <span class="token operator">=</span> <span class="token number">2.1</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">let</span> foo <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BasicVarGen</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">let</span> bar <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BasicVarGen</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token keyword">debugger</span>

bar<span class="token punctuation">.</span>heapNumber1 <span class="token operator">++</span>
bar<span class="token punctuation">.</span>sim1 <span class="token operator">++</span></code></pre>
<pre class="language-diff" data-language="diff"><code class="language-diff">BasicVarGen×2	

<span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line"> BasicVarGen@5713
</span><span class="token prefix unchanged"> </span><span class="token line">   map::system / Map@59709
</span><span class="token prefix unchanged"> </span><span class="token line">   __proto__::Object@59707
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   heapNumber1::heap number@59687
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   heapNumber1::heap number@59701
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   heapNumber2::heap number@59691
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   heapNumber2::heap number@59703
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   heapNumber3::heap number@59697
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   heapNumber3::heap number@59705
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   smi1::smi number@30901🗖
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   sim1::heap number@64357
</span><span class="token prefix inserted">+</span><span class="token line">   smi1::smi number@64483🗖
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   smi2::smi number@30901🗖
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   smi2::smi number@64483🗖
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   smi3::smi number@34275🗖
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   smi3::smi number@64505🗖
</span></span>
<span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line"> BasicVarGen@5715
</span><span class="token prefix unchanged"> </span><span class="token line">   map::system / Map@59709
</span><span class="token prefix unchanged"> </span><span class="token line">   __proto__::Object@59707
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   heapNumber1::heap number@59701
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   heapNumber1::heap number@59687
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   heapNumber2::heap number@59703
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   heapNumber2::heap number@59691
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   heapNumber3::heap number@59705
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   heapNumber3::heap number@59697
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   smi1::smi number@30901🗖
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   smi1::smi number@64483🗖
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   smi2::smi number@30901🗖
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   smi2::smi number@64483🗖
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   smi3::smi number@34275🗖
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   smi3::smi number@64505🗖</span></span></code></pre>
<p>可以看到在变量修改时, 所有变量都变了</p>
<p>结论: <code>smi</code>存储在栈, 其他存储在堆</p>
<h4 id="oddball-类型与-boolean-undefined-null">OddBall 类型与 Boolean
&amp; Undefined &amp; null</h4>
<p><code>OddBall</code>是V8中的一个数据类型,
<code>Oddball</code>继承于<code>HeapObject</code>,
而<code>HeapObject</code>继承于<code>Object</code></p>
<p>简单的看下Boolean &amp; Undefined &amp; null</p>
<pre class="language-js" data-language="js"><code class="language-js"><span class="token keyword">const</span> <span class="token function-variable function">BasicVarGen</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>a <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>b <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>c <span class="token operator">=</span> <span class="token keyword">undefined</span><span class="token punctuation">;</span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>d <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">let</span> foo <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BasicVarGen</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">let</span> bar <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BasicVarGen</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token keyword">debugger</span>

foo<span class="token punctuation">.</span>a <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
foo<span class="token punctuation">.</span>b <span class="token operator">=</span> <span class="token operator">!</span><span class="token punctuation">(</span><span class="token number">1</span> <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
foo<span class="token punctuation">.</span>c <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
foo<span class="token punctuation">.</span>d <span class="token operator">=</span> <span class="token keyword">undefined</span><span class="token punctuation">;</span></code></pre>
<pre class="language-diff" data-language="diff"><code class="language-diff">BasicVarGen×2	
<span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line"> BasicVarGen@5713
</span><span class="token prefix unchanged"> </span><span class="token line">   map::system / Map@59603
</span><span class="token prefix unchanged"> </span><span class="token line">   __proto__::Object@59601
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   d::system / Oddball@69🗖
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   d::system / Oddball@65🗖
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   c::system / Oddball@65🗖
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   c::system / Oddball@69🗖
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   b::system / Oddball@73
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   b::system / Oddball@71
</span></span><span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">   a::system / Oddball@71🗖
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">   a::system / Oddball@73🗖
</span></span><span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line"> BasicVarGen@5715
</span><span class="token prefix unchanged"> </span><span class="token line">   map::system / Map@59603
</span><span class="token prefix unchanged"> </span><span class="token line">   __proto__::Object@59601
</span><span class="token prefix unchanged"> </span><span class="token line">   d::system / Oddball@69🗖
</span><span class="token prefix unchanged"> </span><span class="token line">   c::system / Oddball@65🗖
</span><span class="token prefix unchanged"> </span><span class="token line">   b::system / Oddball@73
</span><span class="token prefix unchanged"> </span><span class="token line">   a::system / Oddball@71🗖</span></span></code></pre>
<p>看到了<code>OddBall</code>类型, 发现同一值的地址也是相同的. 在赋值时,
也是就地复用. (而且这些拓展自<code>oddBall</code>的基本类型,
其地址是固定的, 也就是说, 在V8跑起来的第一时间,
不管我们有没有声明这些基本类型, 他们都已经被创建完毕了.
而我们声明对象时, 赋的是他们的引用.
这也可以解释为什么我们说基本类型是赋到栈中: 在V8中,
存放在<code>@73</code>的值, 永远是空字符串,
那么v8就可以等效把这些地址视为值本身. )</p>
<p><strong>小结</strong></p>
<ul>
<li>字符串: 存在堆里, 栈中为引用地址, 如果存在相同字符串,
则引用地址相同.</li>
<li>数字: 小整数存在栈中, 其他类型存在堆中.</li>
<li>其他类型: 引擎初始化时分配唯一地址, 栈中的变量存的是唯一的引用.</li>
</ul>
<h3 id="参考资料">参考资料</h3>
<ul>
<li><a
target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/362219811">zhihu-葡萄zi-JavaScript中变量到底是存储在「栈」还是「堆」上</a>
<a target="_blank" rel="noopener" href="https://archive.ph/oRv1I">Archive</a></li>
<li><a
target="_blank" rel="noopener" href="https://www.zhihu.com/question/482433315/answer/2083349992">zhihu-六耳-JavaScript中变量到底是存储在「栈」还是「堆」上</a>
<a target="_blank" rel="noopener" href="https://archive.ph/aYqlf">Archive</a></li>
<li><a
target="_blank" rel="noopener" href="https://hashnode.com/post/does-javascript-use-stack-or-heap-for-memory-allocation-or-both-cj5jl90xl01nh1twuv8ug0bjk">Marco
Alka - Does JavaScript use stack or heap for memory allocation or
both?</a></li>
</ul>

    </div>

    
    
    
      


    <footer class="post-footer">
          <div class="reward-container">
  <div></div>
  <button>
    赞赏
  </button>
  <div class="post-reward">
      <div>
        <img src="/images/wechatpay.png" alt="Liu Kairui 微信">
        <span>微信</span>
      </div>
      <div>
        <img src="/images/alipay.png" alt="Liu Kairui 支付宝">
        <span>支付宝</span>
      </div>

  </div>
</div>

          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>Liu Kairui
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://liukairui.me/article/JavaScript%E5%8F%98%E9%87%8F%E5%AD%98%E5%82%A8%E6%9C%BA%E5%88%B6/" title="JavaScript变量存储机制">http://liukairui.me/article/JavaScript变量存储机制/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/%E5%89%8D%E7%AB%AF/" rel="tag"><i class="fa fa-tag"></i> 前端</a>
              <a href="/tags/JS%E8%AF%AD%E6%B3%95/" rel="tag"><i class="fa fa-tag"></i> JS语法</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/article/2022%E5%AE%9E%E4%B9%A0%E5%88%B7%E9%A2%98/" rel="prev" title="2022实习刷题🔒">
                  <i class="fa fa-chevron-left"></i> 2022实习刷题🔒
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/article/JavaScript%E7%BA%A2%E5%AE%9D%E4%B9%A6%E6%9F%A5%E6%BC%8F%E8%A1%A5%E7%BC%BA/" rel="next" title="JavaScript红宝书查漏补缺🔒">
                  JavaScript红宝书查漏补缺🔒 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments" id="valine-comments"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2019 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Liu Kairui</span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>
  <div class="addthis_inline_share_toolbox">
    <script src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-6231eb6f709fc868" async="async"></script>
  </div><script
  async
  src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"
></script>

 
<script src="https://cdn.jsdelivr.net/npm/moment@2.22.2/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment-precise-range-plugin@1.3.0/moment-precise-range.min.js"></script>
<script>
  function timer() {
    var ages = moment.preciseDiff(moment(),moment(20201101,"YYYYMMDD"));
    ages = ages.replace(/years?/, "年");
    ages = ages.replace(/months?/, "月");
    ages = ages.replace(/days?/, "天");
    ages = ages.replace(/hours?/, "小时");
    ages = ages.replace(/minutes?/, "分");
    ages = ages.replace(/seconds?/, "秒");
    ages = ages.replace(/\d+/g, '<span class="daysCnt" style="color:#1890ff">$&</span>');
    div.innerHTML = `我已在此等候你 ${ages}`;
    div.className="workDays";
  }
  var div = document.createElement("div");
  //插入到copyright之后
  var copyright = document.querySelector(".copyright");
  document.querySelector(".footer-inner").insertBefore(div, copyright.nextSibling);
  timer();
  setInterval("timer()",1000)
</script>



    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@next-theme/pjax@0.5.0/pjax.min.js" integrity="sha256-3NkoLDrmHLTYj7csHIZSr0MHAFTXth7Ua/DDt4MRUAg=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js" integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pangu/4.0.7/pangu.min.js"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  
<script src="https://cdn.jsdelivr.net/npm/hexo-generator-searchdb@1.4.0/dist/search.js" integrity="sha256-vXZMYLEqsROAXkEw93GGIvaB2ab+QW6w3+1ahD9nXXA=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>


  <script class="next-config" data-name="mermaid" type="application/json">{"enable":true,"theme":"forest","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mermaid/8.14.0/mermaid.min.js","integrity":"sha256-7wT34TI0pEBeEFoi4z+vhuSddGh6vUTMWdqJ2SDe2jg="}}</script>
  <script src="/js/third-party/tags/mermaid.js"></script>

  <script src="/js/third-party/fancybox.js"></script>

  <script src="/js/third-party/pace.js"></script>

  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>


  <script class="next-config" data-name="leancloud_visitors" type="application/json">{"enable":true,"app_id":"ABKlVtS4cyaWYEwunPyK3sXt-9Nh9j0Va","app_key":"xxGXdTTEGEVifs2TLB35844I","server_url":"https://abklvts4.lc-cn-e1-shared.com","security":false}</script>
  <script src="/js/third-party/statistics/lean-analytics.js"></script>


  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","mhchem":true,"js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.0/es5/tex-mml-chtml.min.js"}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


  <script src="https://cdnjs.cloudflare.com/ajax/libs/quicklink/2.2.0/quicklink.umd.js" integrity="sha256-4kQf9z5ntdQrzsBC3YSHnEz02Z9C1UeW/E9OgnvlzSY=" crossorigin="anonymous"></script>
  <script class="next-config" data-name="quicklink" type="application/json">{"enable":true,"home":false,"archive":false,"delay":true,"timeout":3000,"priority":true,"url":"http://liukairui.me/article/JavaScript%E5%8F%98%E9%87%8F%E5%AD%98%E5%82%A8%E6%9C%BA%E5%88%B6/"}</script>
  <script src="/js/third-party/quicklink.js"></script>
<script src="https://cdn.jsdelivr.net/npm/darkmode-js@1.5.7/lib/darkmode-js.min.js"></script>

<script>
var options = {
  bottom: '64px',
  right: 'unset',
  left: '32px',
  time: '0.5s',
  mixColor: 'transparent',
  backgroundColor: 'transparent',
  buttonColorDark: '#100f2c',
  buttonColorLight: '#fff',
  saveInCookies: true,
  label: '🌓',
  autoMatchOsTheme: true
}
const darkmode = new Darkmode(options);
window.darkmode = darkmode;
darkmode.showWidget();
</script>


<script class="next-config" data-name="valine" type="application/json">{"enable":true,"appId":"ABKlVtS4cyaWYEwunPyK3sXt-9Nh9j0Va","appKey":"xxGXdTTEGEVifs2TLB35844I","serverURLs":"https://abklvts4.lc-cn-e1-shared.com","placeholder":"请开始你的表演","avatar":"identicon","meta":["nick","mail","link"],"pageSize":10,"lang":"zh-CN","visitor":false,"comment_count":true,"recordIP":true,"enableQQ":true,"requiredFields":[],"el":"#valine-comments","path":"/article/JavaScript%E5%8F%98%E9%87%8F%E5%AD%98%E5%82%A8%E6%9C%BA%E5%88%B6/"}</script>
<script>
document.addEventListener('page:loaded', () => {
  NexT.utils.loadComments(CONFIG.valine.el)
    .then(() => NexT.utils.getScript(
      'https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js',
      { condition: window.Valine }
    ))
    .then(() => {
      new Valine(CONFIG.valine);
    });
});
</script>


  <script async src="/js/fireworks.js"></script>




  <script src="/js/activate-power-mode.min.js"></script>
  <script>
    POWERMODE.colorful = true;
    POWERMODE.shake = false;
    document.body.addEventListener('input', POWERMODE);
  </script>




  <script src="/js/wobblewindow.js"></script>
  <script>
    //只在桌面版网页启用特效 记得同步到header.njk
    if( window.innerWidth > 768  ){
      $(document).ready(function () {
        
          $('body>main>header').wobbleWindow({
            radius: 50,
            movementTop: false,
            movementLeft: false,
            movementRight: false,
            debug: false,
          });
        

        //
        //  $('body header>aside').wobbleWindow({
        //    radius: 50,
        //    movementLeft: false,
        //    movementTop: false,
        //    movementBottom: false,
        //    position: 'fixed',
        //    debug: false,
        //  });
        //

        
          $('body>footer').wobbleWindow({
            radius: 50,
            movementBottom: false,
            movementLeft: false,
            movementRight: false,
            debug: false,
          });
        
      });
    }
  </script>


 
<script>
  $(document).ready(function(){
    var beian = document.querySelector(".footer-inner > .beian > a");
    var cpr=document.querySelector(".footer-inner > .copyright");
    var cnz=document.querySelector(".workDays");//.parentNode;
    var bsz=document.querySelector(".busuanzi-count");
    if(cnz!=null&&bsz!=null)
      cnz.parentNode.insertBefore(bsz,cnz);
    if(bsz == null || bsz == undefined || document.querySelector("#busuanzi_value_site_pv").innerText=="" || document.querySelector("#busuanzi_value_site_uv").innerText == "")
      bsz.remove();
    checkIndex();
    if(beian){cpr.classList.add('split-line');cpr.appendChild(beian);}
  })
  $(document).on('pjax:complete',checkIndex);
</script>



<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":false},"react":{"opacity":0.7}});</script></body>
</html>
